package com.hm.hiedict.sql;

import com.hm.hiedict.util.HiWordData;
import ohos.app.AbilityContext;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;

public class HiSql {
    private AbilityContext context;
    private File dictPath;
    private File dbPath;
    private RdbStore store;
    private StoreConfig config = StoreConfig.newDefaultConfig("dict.sqlite");
    private static final RdbOpenCallback callback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore rdbStore) {

        }

        @Override
        public void onUpgrade(RdbStore rdbStore, int i, int i1) {

        }
    };

    public HiSql(AbilityContext context){
        this.context = context;
        this.dictPath = new File(context.getDatabaseDir().toString() +
                "/db");
        if (!dictPath.exists()){
            dictPath.mkdir();
        }
        dbPath = new File(Paths.get(dictPath.toString(), "dict.sqlite").toString());
    }

    public RdbStore getStore(){
        return store;
    }

    private void extractDB() throws IOException{
        //读取dict.sqlite文件的字节流
        Resource resource = context.getResourceManager().getRawFileEntry(
                "resources/rawfile/dict.sqlite").openRawFile();
        if (dbPath.exists()){
            dbPath.delete();
        }

        FileOutputStream fos = new FileOutputStream(dbPath);
        byte[] buffer = new byte[4096];
        int count = 0;
        while ((count = resource.read(buffer)) >= 0){
            fos.write(buffer, 0, count);
        }
        resource.close();
        fos.close();
    }

    public void init() throws IOException{
        extractDB();
        // 打开数据库
        DatabaseHelper helper = new DatabaseHelper(context);
        store = helper.getRdbStore(config, 1, callback, null);
    }

    //搜索本地词库
    public ArrayList<HiWordData> searchLocalDict(String word){
        word = word.toLowerCase();
        String[] args = new String[]{word};
        ResultSet resultSet = store.querySql("select * from t_words where word=?", args);
        ArrayList<HiWordData> result = new ArrayList<>();
        while (resultSet.goToNextRow()){
            HiWordData hiWordData = new HiWordData();
            hiWordData.type = resultSet.getString(2);
            hiWordData.meanings = resultSet.getString(3);
            result.add(hiWordData);
        }
        resultSet.close();
        return result;
    }
}
